/**
 * Created by wangjz on 2018/11/27.
 */
import React, { Component } from 'react';
import { Menu } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';

const MyIcon = createFromIconfontCN({
  scriptUrl: 'public/icon/all.js',
});
const SubMenu = Menu.SubMenu;

class SiderMenu extends Component {
  state = {
    current: '',
    openKeys: [],
  };

  rootSubmenuKeys = [];

  onOpenChange = openKeys => {
    const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);

    let latesItem;
    for (let item of this.props.dataSource) {
      if (item.id == latestOpenKey) {
        latesItem = item;
        break;
      }
    }

    if (latesItem) {
      this.setState({
        openKeys: latestOpenKey ? [latestOpenKey] : [],
      });
    }else {
      this.setState({ openKeys });
    }
  };

  subMenu = children => {
    if (children == null) {
      return null;
    }
    let childrenNode = [];
    for (let item of children) {
      item.children ?
        childrenNode.push(<SubMenu key={item.id}
                                   title={<span>{item.icon ? <MyIcon type={item.icon}/> : ''}
                                     <span>{item.name}</span></span>}>
          {this.subMenu(item.children)}
        </SubMenu>)
        :
        childrenNode.push(<Menu.Item key={item.id}>
          {item.icon ? <MyIcon type={item.icon}/> : ''} <span>{item.name}</span>
        </Menu.Item>);
    }
    return childrenNode;
  };

  /**
   * 点击菜单
   * @param item
   * @param key
   * @param keyPath
   */
  handleLeftClickMenu = ({ item, key, keyPath }) => {
    this.setState({ current: key });
    if (this.props.onSelect) {
      this.props.onSelect(key);
    }
  };

  render() {
    return (
      <div style={{ width: '100%', height: '100%', overflow: 'auto' }}>
        <Menu
          openKeys={this.state.openKeys}
          onOpenChange={this.onOpenChange}
          onClick={this.handleLeftClickMenu.bind(this)}
          selectedKeys={[this.state.current]}
          style={{ width: 'calc(100% - 1px)', borderRight: '0px solid #e8e8e8' }}
          mode="inline"
          theme={this.props.theme}>
          {this.subMenu(this.props.dataSource)}
        </Menu>
      </div>
    );
  }
}

export default SiderMenu;
